﻿using Circus.Utility;
using Circus.Utility.Json;
using System;

namespace WoAiPao {

    /// <summary>
    /// 提供调试相关接口。
    /// </summary>
    public static class DebugController {

        /// <summary>
        /// 获取所有 API 列表。
        /// </summary>
        /// <returns></returns>
        public static object getApiList() {

            JsonObject obj = new JsonObject();

            Type[] types;
            try {
                types = typeof (ApiHandler).Assembly.GetTypes();
            } catch (TypeLoadException e) {
                return e.Message;
            }

            foreach (var type in types) {
                if (type.Name.EndsWith(ApiHandler.typePostfix)) {

                    JsonObject typeObj = new JsonObject();

                    foreach (var method in type.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)) {

                        JsonObject methodObj = new JsonObject();

                        methodObj["type"] = method.GetCustomAttributes(typeof(postAttribute), false).Length > 0 ? "POST" : "GET";

                        JsonObject paramsObj = new JsonObject();

                        foreach (var param in method.GetParameters()) {

                            JsonObject paramObj = new JsonObject();

                            paramObj["type"] = param.ParameterType.FullName;
                            paramObj["defaultValue"] = param.DefaultValue;

                            paramsObj[param.Name] = paramObj;

                        }

                        methodObj["params"] = paramsObj;
                        methodObj["returns"] = method.ReturnType.FullName;

                        typeObj[method.Name] = methodObj;

                    }

                    obj[decemeralCase(type.Name.Substring(0, type.Name.Length - ApiHandler.typePostfix.Length))] = typeObj;

                }
            }

            return obj;

        }

        private static string decemeralCase(string s) {
            if (String.IsNullOrEmpty(s)) {
                return s;
            }
            return s[0].ToString().ToLowerInvariant() + s.Substring(1);
        }


        public static void test() {

        }

    }

}